﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyWebAPI.Controllers
{
    [Route("[Controller]")]
    public class StudentController : Controller
    {
        private Context.MyContext _ctx;

        public StudentController(Context.MyContext ctx)
        {
            this._ctx = ctx;
        }

        /// <summary>
        /// 按学号获取学生信息
        /// </summary>
        /// <param name="stuNo">学号</param>
        /// <returns>学生信息</returns>
        [HttpGet]
        [Route("Get")]
        public IActionResult GetStudent(String stuNo)
        {
            var model = _ctx.Set<Models.Student>().FirstOrDefault(s => s.StuNo==stuNo);
            return Ok(model);//200staus
        }

        [HttpGet]
        [Route("List/{name}")]
        public List<Models.Student> GetStudents(String name)
        {
            var models = _ctx.Set<Models.Student>().Where(s => s.StuName.Contains(name)).ToList();
            return models;
        }

        [HttpPost]
        [Route("Add")]
        public IActionResult Add([FromBody]Models.Student s) //默认从Form中取数据；如果通过jquery.ajax方式传递过来的数据，存在Body中
        {
            try
            {
                _ctx.Set<Models.Student>().Add(s);
                _ctx.SaveChanges();
                return Ok(true);
            }
            catch
            {
                return Ok(false);
            }
        }
    }
}
